<?php
/**
 * Created by PhpStorm.
 * User: FDG296
 * Date: 2017/7/10
 * Time: 14:56
 */
namespace backend\controllers;

use backend\models\UserMaster;
use backend\models\UserRoleGroup;
use common\models\CustMaster;
use Yii;
use yii\web\AdminController;
use backend\models\UserDepartment;
use backend\models\UserRole;
use backend\models\UserMappedRole;
use yii\data\Pagination;
use common\helps;

class SysUserController extends AdminController{
    public $layout = false;
    //业务关键字
    public $service = 'SysUser';

    /**
     * 局部关闭csrf
     * action 方法名
     */
    public function beforeAction($action){

        $currentaction = $action->id;

        $novalidactions = ['update-user','update-password','add-user','disable-user','enable-user'];

        if(in_array($currentaction,$novalidactions)) {

            $action->controller->enableCsrfValidation = false;

        }
        parent::beforeAction($action);

        return true;
    }


	/**
	 *
	 */
	public function actionUpdatePassword(){

		//取得登录信息
		$redisHelper	= new helps\redisHelper();
		$uerInfo	= $redisHelper->getloginUserInfo();


		//查询当前登录的用户信息
		if(!$userMasterInfo	= UserMaster::find()->where(['id'=>$uerInfo->userId])->one()){
			$this->retJson('暂无此用户信息',500);
		}

		if($data =Yii::$app->request->post()){

			//密码不相同
			if($data['user_pwd']!=$data['user_pwd_re']){
				$this->retJson('修改失败',500);
			}

			$data_now['user_pwd'] = helps\tools::md5pwd($data['user_pwd']);
			
			$data_now['true_name']  	= $data['true_name'];
			$data_now['edit_time'] 	= date('Y-m-d H:i:s',time());
			$data_now['editor'] 	=$uerInfo->userName;
			$data_now['mobile'] 	= $data['mobile'];

			$res = UserMaster::updateAll($data_now, " id = ".$uerInfo->userId);
			if($res > 0){
				//
				$this->saveLog($this->service,'用户修改密码','MOD', '更新用户 ID = '. $uerInfo->userId . "\r\n" .\yii\helpers\Json::encode($data_now));
				$this->retJson('用户修改成功',200);
			}else{
				$this->retJson('用户修改失败',500);
			}

		}

		return $this->render('update-password',['userMasterInfo'=>$userMasterInfo]);
	}

    /**
     *用户管理页
     */
    public function actionIndex()
    {

        $list = $this->getDepartTree();
        $group_list = UserRoleGroup::find()->where(array('use_flg' => 1))->asArray()->all();
        foreach ($group_list as &$value) {
            $where['use_flg'] = 1;
            $where['role_group_id'] = $value['id'];
            $value['role_list'] = UserRole::find()->where($where)->asArray()->all();
        }

        //$role_list = UserRole::find()->where(array('use_flg'=>1))->asArray()->all();
        $this->saveLog($this->service, '用户查询', 'VIEW', '');

        $sql = 'select ShopID,ShopName from j_shop';
        $shops = Yii::$app->db->createCommand($sql)->queryAll();

        return $this->render('index', ['tree_list' => \yii\helpers\Json::encode($list), 'group_list' => $group_list, 'shops' => $shops]);
    }

    /**
     * 部门
     */
    public function getDepartTree(){
        $list = UserDepartment::find()->where(array('use_flg'=>UserDepartment::STATUS_ENABLE))->orderBy(array('sort'=>SORT_ASC))->asArray()->all();
        $tree_list = array();
        $tree_list[0]['id'] = '';
        $tree_list[0]['pId'] = '';
        $tree_list[0]['name'] = '顶级部门';
        foreach($list as $key=>$value){
            $tree_list[$key+1]['id'] = $value['id'];
            $tree_list[$key+1]['pId'] = $value['parent_id'];
            $tree_list[$key+1]['name'] = $value['dept_name'];
        }
        return $tree_list;
    }

    /**
     * 获取用户列表
     */
    public function actionGetUserList(){
        $data = Yii::$app->request->post();

        $condition = array();
        if(!empty($data['user_name'])){
            $condition = ['like', 'user_name', $data['user_name']];
        }
        if(!empty($data['true_name'])){
            $condition = ['like', 'true_name', $data['true_name']];
        }
        if(!empty($data['user_name']) && !empty($data['true_name'])){
            $condition = ['and', ['like', 'user_name', $data['user_name']], ['like', 'true_name', $data['true_name']]];
        }
        $query = UserMaster::find()->where($condition)->select('id,user_name,true_name,dept_id,dept_name,mobile,email,sex,last_login_time,last_login_ip,use_flg');
        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);
        //$pagination->defaultPageSize = $data['length'];

        $list = $query->offset($data['start'])->limit($data['length'])
            ->orderBy(array('id'=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->all();
        if(empty($list)){
            $list = array();
        }

        //相关参数   http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    /**
     * 增加后台用户
     */
    public function actionAddUser()
    {
        $model = new UserMaster();
        $data = Yii::$app->request->post();


        $shopIds = isset($data['shops']) ? implode(',', $data['shops']) : null;

        $data_now['user_name'] = trim($data['user_name']);

        $result = $model->findByUsername($data_now['user_name']);
        if ($result) {
            $this->retJson('用户名已经存在！', 500);
        }

        $data_now['user_pwd'] = helps\tools::md5pwd($data['user_pwd']);
        $data_now['dept_name'] = $data['dept_name'];
        $data_now['dept_id'] = $data['dept_id'];
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['true_name'] = $data['true_name'];
        $data_now['create_time'] = date('Y-m-d H:i:s', time());
        $data_now['creator'] = $model->getCreator();
        $data_now['mobile'] = $data['mobile'];
        $data_now['email'] = $data['email'];
        $data_now['sex'] = $data['sex'];
        $data_now['shop_ids'] = $shopIds;

        $res = Yii::$app->db->createCommand()->insert('j_user_master', $data_now)->execute();
        if ($res > 0) {
            $this->saveLog($this->service, '增加用户', 'ADD', '新增用户：' . $data_now['user_name'] . "\r\n" . \yii\helpers\Json::encode($data_now));
            $this->retJson('用户增加成功', 200);
        } else {
            $this->retJson('用户增加失败', 500);
        }
    }

    /*
     * 根据id获取用户信息
     */
    public function actionGetOneUser(){
        $data = Yii::$app->request->post();

        $result = UserMaster::findOne(array('id'=>$data['id']));
        unset($result['user_pwd']);
        return \yii\helpers\Json::encode($result);
    }

    /**
     * 修改用户信息
     */
    public function actionUpdateUser()
    {
        $model = new UserMaster();
        $data = Yii::$app->request->post();
        $shopIds = isset($data['shops']) ? implode(',', $data['shops']) : null;
        $data_now['dept_name'] = $data['dept_name'];
        $data_now['dept_id'] = $data['dept_id'];
        $data_now['true_name'] = $data['true_name'];
        $data_now['edit_time'] = date('Y-m-d H:i:s', time());
        $data_now['editor'] = $model->getCreator();
        $data_now['mobile'] = $data['mobile'];
        $data_now['email'] = $data['email'];
        $data_now['sex'] = $data['sex'];
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['shop_ids'] = $shopIds;
        $res = $model::updateAll($data_now, " id = " . $data['id']);
        if ($res > 0) {
            $this->saveLog($this->service, '更新用户', 'MOD', '更新用户 ID = ' . $data['id'] . "\r\n" . \yii\helpers\Json::encode($data_now));
            $this->retJson('用户修改成功', 200);
        } else {
            $this->retJson('用户修改失败', 500);
        }
    }

    /**
     * 禁用用户
     */
    public function actionDisableUser(){
        $model = new UserMaster();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 0;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, " id = ".$data['id']);

        if($res > 0){
            $this->saveLog($this->service,'用户禁用','USEFLG0', '用户 ID = '. $data['id'] );
            $this->retJson('用户禁用成功',200);
        }else{
            $this->retJson('用户禁用失败',500);
        }
    }

    /**
     * 启用用户
     */
    public function actionEnableUser(){
        $model = new UserMaster();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 1;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, " id = ".$data['id']);

        if($res > 0){
            $this->saveLog($this->service,'用户启用','USEFLG1', '用户 ID = '. $data['id'] );
            $this->retJson('用户启用成功',200);
        }else{
            $this->retJson('用户启用失败',500);
        }
    }

    public function actionGetMappedRole(){
        $data = Yii::$app->request->post();
        $result = UserMappedRole::findOne(array('user_id'=>$data['user_id']));
        return \yii\helpers\Json::encode($result);
    }

    //用户角色映射
    public function actionUserMappedRole(){
        $model = new UserMappedRole();
        $data = Yii::$app->request->post();

        if(empty($data['role_id'])){
            $data['role_id'] = '';
        }else{
            $data['role_id'] = implode(',',$data['role_id']);
        }

        $result = UserMappedRole::findOne(array('user_id'=>$data['user_id']));
        if(empty($result)){
            //新增
            $data_now['user_id'] = $data['user_id'];
            $data_now['role_id'] = $data['role_id'];
            $data_now['create_time'] = date('Y-m-d H:i:s',time());
            $data_now['creator'] = $model->getCreator();
            $data_now['memo'] = $data['memo'];
            $log_data = \yii\helpers\Json::encode($data_now);
            $res = Yii::$app->db->createCommand()->insert('j_user_mapped_role',$data_now)->execute();
        }else{
            //编辑
            $mod_data['role_id'] = $data['role_id'];
            $mod_data['editor'] = $model->getCreator();
            $mod_data['edit_time'] = date('Y-m-d H:i:s',time());
            $mod_data['memo'] = $data['memo'];
            $log_data = \yii\helpers\Json::encode($mod_data);
            $res = $model::updateAll($mod_data, " user_id = ".$data['user_id']);
        }
        if($res > 0){
            $this->saveLog($this->service,'设置用户角色','MOD', '用户 ID = '. $data['user_id'] . "\r\n" . $log_data);
            $this->retJson('设置成功',200);
        }else{
            $this->retJson('设置失败',500);
        }
    }
}